import os
import re
import argparse
from pathlib import Path

def search_files(root_dir, search_term, search_content=False, 
                case_sensitive=False, recursive=True, ext_filter=None):
    """
    搜索文件
    :param root_dir: 根目录
    :param search_term: 搜索词（支持正则）
    :param search_content: 是否搜索文件内容
    :param case_sensitive: 是否区分大小写
    :param recursive: 是否递归搜索
    :param ext_filter: 过滤文件扩展名
    """
    try:
        # 编译正则表达式
        flags = 0 if case_sensitive else re.IGNORECASE
        pattern = re.compile(search_term, flags)
        
        # 处理文件扩展名过滤
        extensions = [ext.lower() for ext in ext_filter.split(',')] if ext_filter else None
        
        # 统计结果
        file_count = 0
        match_count = 0
        results = []
        
        # 遍历目录
        for entry in Path(root_dir).rglob('*') if recursive else Path(root_dir).glob('*'):
            if entry.is_file():
                file_count += 1
                
                # 过滤文件扩展名
                if extensions:
                    file_ext = entry.suffix.lower()
                    if file_ext not in extensions and f".{file_ext}" not in extensions:
                        continue
                
                # 搜索文件名
                if pattern.search(str(entry.name)):
                    results.append(f"文件名匹配: {entry}")
                    match_count += 1
                    continue
                
                # 搜索文件内容
                if search_content:
                    # 只处理文本文件
                    text_extensions = ('.txt', '.md', '.html', '.py', '.java', '.csv', '.log')
                    if entry.suffix.lower() in text_extensions:
                        try:
                            with open(entry, 'r', encoding='utf-8', errors='ignore') as f:
                                content = f.read()
                                if pattern.search(content):
                                    results.append(f"内容匹配: {entry}")
                                    match_count += 1
                        except:
                            continue
        
        # 显示结果
        print(f"搜索完成！共扫描 {file_count} 个文件，找到 {match_count} 个匹配项\n")
        for result in results:
            print(result)
        
    except Exception as e:
        print(f"搜索失败: {str(e)}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='本地文件搜索工具')
    parser.add_argument('directory', help='搜索目录')
    parser.add_argument('term', help='搜索词（支持正则表达式）')
    parser.add_argument('--content', action='store_true', help='搜索文件内容而非文件名')
    parser.add_argument('--case-sensitive', action='store_true', help='区分大小写')
    parser.add_argument('--no-recursive', action='store_false', dest='recursive', 
                      help='不递归搜索子目录')
    parser.add_argument('--ext', help='过滤文件扩展名，用逗号分隔，如txt,py')
    
    args = parser.parse_args()
    
    search_files(
        root_dir=args.directory,
        search_term=args.term,
        search_content=args.content,
        case_sensitive=args.case_sensitive,
        recursive=args.recursive,
        ext_filter=args.ext
    )
